#include <iostream>
#include <mutex>
#include <thread>

using std::cout;
using std::endl;
using std::mutex;
using std::thread;

int gCnt = 0;
mutex mtx;//创建了互斥锁的对象

class MutexLockGuard
{
public:
    MutexLockGuard()
    {
        _mutex.lock();
    }

    ~MutexLockGuard()
    {
        _mutex.unlock();
    }
private:
    mutex _mutex;
};

void threadFunc()
{
    for(size_t idx = 0; idx != 10000000; ++idx)
    {
        //C++11中提出来的std::mutex可以会有隐患，使用的时候
        //如果只上锁，没有解锁，就会造成死锁
        mtx.lock();
        ++gCnt;//对共享资源进行写操作的时候，要上锁
        mtx.unlock();
    }
}

int main(int argc, char *argv[])
{
    thread th1(threadFunc);
    thread th2(threadFunc);

    th1.join();
    th2.join();
    cout << "gCnt = " << gCnt << endl;

    return 0;
}

